﻿namespace ChinaUnicom.Models
{
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Collections.Specialized;
    using System.Linq;
    using ChinaUnicom.Exceptions;

    public class ItemCollection : Collection<Item>, INotifyCollectionChanged
    {
        public ItemCollection()
        {
        }

        protected override void ClearItems()
        {
            base.ClearItems();
            if (CollectionChanged != null)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
            }
        }

        protected override void InsertItem(int index, Item item)
        {
            if (item == null || string.IsNullOrEmpty(item.Name))
            {
                throw new UnicomException("item is null or the name of the item is null.");
            }

            base.InsertItem(index, item);
            if (CollectionChanged != null)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, item, index));
            }
        }

        protected override void RemoveItem(int index)
        {
            var item = this[index];
            base.RemoveItem(index);
            if (CollectionChanged != null)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, item, index));
            }
        }

        protected override void SetItem(int index, Item item)
        {
            var old = this[index];
            base.SetItem(index, item);
            if (CollectionChanged != null)
            {
                CollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, item, old, index));
            }
        }

        public void Add(IEnumerable<Item> items)
        {
            if (items == null)
            {
                return;
            }

            foreach (var item in items)
            {
                Add(item);
            }
        }

        public void Add(string name, string value)
        {
            Add(new Item { Name = name, Value = value });
        }

        public override string ToString()
        {
            return string.Join(", ", this.Select(x => x.ToString()));
        }

        public event NotifyCollectionChangedEventHandler CollectionChanged;
    }
}
